/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gui.filetree;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeModel;

import objects.data.WorkPacket;
import utils.Utils;

import filesystem.CFile;
import filesystem.FileSystem;
import gui.GUIUtils;
import gui.main.MainPanelGUIView;

/**
 *
 * @author simonk
 */
public class TreeUtils {
	public static Map<CFile,TreeNode> treeeMap = new HashMap<CFile,TreeNode>();
	public static TreeNode rootNode = new TreeNode("Home");
	public static JTree fileTree = null;
	
	public static void insertSecondLevelNode(TreeNode newNode) {
		DefaultTreeModel model = (DefaultTreeModel) fileTree.getModel();
		model.insertNodeInto(newNode, rootNode, rootNode.getChildCount());
		rootNode.add(newNode);
	}
	
	public static void insertNode(TreeNode parent, TreeNode newNode) {
		DefaultTreeModel model = (DefaultTreeModel) fileTree.getModel();
		model.insertNodeInto(newNode, parent, parent.getChildCount());
		parent.add(newNode);
	}
	
	public static void insertFromWorkPacket(WorkPacket workPacket) {
		FileSystem fs = Utils.userInfo.fs;
		TreeNode node = new TreeNode(workPacket.jobname);
		insertSecondLevelNode(node);
		insertNode(node,new TreeNode(new File(workPacket.sourceDir)));
		refreshTree();
		CFile first = new CFile(workPacket.jobname);
		CFile second = new CFile(new File(workPacket.sourceDir));
		long parent = fs.addFileToRoot(first);
		fs.addFile(parent, second);
		fs.sendUpdate();	
	}
	
	public static void createFromFileSystem(FileSystem fs) {
		CFile root = fs.getRoot();
		for(long child : root.getChildren()) {
			addNode(fs, rootNode, fs.getNode(child));
		}
		refreshTree();
	}
	
	public static void addNode(FileSystem fs, TreeNode parent, CFile node) {
		TreeNode newNode = new TreeNode(new TreeNodeInfo(node));
		insertNode(parent, newNode);
		for(long child : node.getChildren()) {
			addNode(fs, newNode, fs.getNode(child));
		}
	}
	
	public static void refreshTree() {
		fileTree.revalidate();
		fileTree.repaint();
	}
	
}
